package com.demo.netty.controller;

import com.alibaba.fastjson.JSON;
import com.demo.netty.client.NettyClient;
import com.demo.netty.dto.ChatDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@Api(tags = "客户端消息发送控制器")
@RestController
@Slf4j
public class ChatController {

    private static String clientId = UUID.randomUUID().toString();

    public static NettyClient bootstrap;


    @ApiOperation("发送消息")
    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public void send(@RequestParam("msg") String msg) {
        if (bootstrap == null) {
            //连接 输入服务器的端口和ip
            try {
                bootstrap = new NettyClient(9999, "127.0.0.1");
            } catch (InterruptedException e) {
                log.error("netty 连接失败!");
            }
        }
        /**
         *   发送消息
         */
        ChatDTO dto = new ChatDTO();
        dto.setClientId(clientId).setMsg(msg);
        /**
         * json字符串发送
         */
        bootstrap.socketChannel.writeAndFlush(JSON.toJSONString(dto));

    }
}